package com.yiboshi.rehrs.feign;

import cn.hutool.core.collection.CollUtil;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.helper.*;
import com.yiboshi.rehrs.util.AperStringUtils;
import com.yiboshi.rehrs.util.SHA256Util;
import com.yiboshi.rehrs.util.StrUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jack 2025/3/23
 */
@Slf4j
public class PosterFeignInterceptor implements RequestInterceptor {

    @Autowired
    ZhongConfigHelper zhongConfigHelper;

    @Autowired
    HelperJinshe helperJinshe;

    @Autowired
    RedisHelper redisHelper;

    static ThreadLocal<Map<String,String>> threadLocalHeader = new ThreadLocal<>();

    static ThreadLocal<ZhongUser> zhongUserThreadLocal = new ThreadLocal<>();


    @Autowired
    ProxyHelper proxyHelper;


    //获取授权header
    @Override
    public void apply(RequestTemplate template) {

        Map<String, String> stringMap = threadLocalHeader.get();
        stringMap.forEach((k,v)->{
            log.info("{},{}",k,v);
            template.header(k,v);
        });


    }

    public static void jdptSign(Map<String, String> tokenMap,ZhongUser zhongUser) {
        String pda_user_token = tokenMap.get("pda_user_token");
        if(pda_user_token==null){
            pda_user_token = "";
        }
        String Jdpt_req_time = (System.currentTimeMillis()+1000+ AperStringUtils.randomNum(2000))+"";
        String person_no = tokenMap.get("person_no");
        String Jdpt_sign = SHA256Util.Jdpt_sign(Jdpt_req_time, pda_user_token,person_no);
        tokenMap.put("jdpt_sign", Jdpt_sign);
        tokenMap.put("jdpt_req_time",Jdpt_req_time);
        String padId = zhongUser.getPadId();
        if(StrUtils.isBlank(padId)){
            padId = zhongUser.getImei();
        }
        if(StrUtils.isNotBlank(padId)){
            tokenMap.put("pda_id",padId);
        }else {
            tokenMap.put("android_id", zhongUser.getAndroidId());
            tokenMap.put("pda_id","");
        }

    }


    public static void setHeader(Map<String,String> header){
        threadLocalHeader.remove();
        threadLocalHeader.set(header);
    }
    public static Map<String, String> getHeader(){
       return  threadLocalHeader.get();
    }

    public static void setHeader(ZhongUser zhongUser){
        zhongUserThreadLocal.remove();
        zhongUserThreadLocal.set(zhongUser);
        threadLocalHeader.remove();
        Map<String, String> stringMap = threadLocalHeader.get();
        if(CollUtil.isEmpty(stringMap)){
            stringMap = new HashMap<>();
            threadLocalHeader.set(stringMap);
        }
        //helperJinshe.vipHeader(zhongUser,null)

    }
}
